﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using EidtTools;
public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// 获取语言标识
    /// </summary>
    private string LanguageTag {
        get { return ViewState["PGLT"].ToString();}
        set { ViewState["PGLT"] = string.IsNullOrEmpty(value) ? "" : "_" + value; }
    }

    string uploadFilePath, uploadFilesSmall;
    string postfixEarliest, postfixSource, postfixSmall, postfixSmallSource, postfixCut;
    public string CutResizeDisabled;
    string cutSize;
    public string CutSizeWidth, CutSizeHeight;
    
    int CountValue = 1;
    public string CutaspectRatio = "0";
    public string IsCutYOrN = "0";

    public static int IsCut = 0;
    public static int IsBtnCut = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获取语种标识
            this.LanguageTag = Request.QueryString["LT"];
        }

        uploadFilePath = ConfigurationManager.AppSettings["UploadFiles"];
        uploadFilesSmall = ConfigurationManager.AppSettings["UploadFilesSmall"];
        postfixEarliest = ConfigurationManager.AppSettings["PostfixEarliest"];
        postfixSource = ConfigurationManager.AppSettings["PostfixSource"];
        postfixSmall = ConfigurationManager.AppSettings["PostfixSmall"];
        postfixSmallSource = ConfigurationManager.AppSettings["PostfixSmallSource"];
        postfixCut = ConfigurationManager.AppSettings["PostfixCut"];
        CutResizeDisabled = ConfigurationManager.AppSettings["CutResizeDisabled"];
        cutSize = ConfigurationManager.AppSettings["CutSize"];
        //smallSize = ConfigurationManager.AppSettings["SmallSize"];
        //smallSourceSize = ConfigurationManager.AppSettings["SmallSourceSize"];
        CutaspectRatio = ConfigurationManager.AppSettings["CutaspectRatio"];
        CountValue = Convert.ToInt32(ConfigurationManager.AppSettings["CountValue"]);
        string[] cutSizeArr = cutSize.Split('*');
        CutSizeWidth = cutSizeArr[0];
        CutSizeHeight = cutSizeArr[1];
    }

    #region Private Methods
    /// <summary>
    /// 消息提示
    /// </summary>
    /// <param name="jsString">消息提示的js代码</param>
    private void RegisterJSMessage(string jsString)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "Info01", jsString);
    }

    /// <summary>
    /// 以顺时针为方向对图像进行旋转、缩放、裁剪
    /// </summary>
    /// <param name="filePath">原始图片物理路径</param>
    /// <param name="cutFilePath">剪切图片物理路径</param>
    /// <param name="angle">旋转角度[0,360](前台给的)</param>
    /// <param name="sx">x方向的比例因子</param>
    /// <param name="sy">y方向的比例因子</param>
    /// <param name="cutRectangle">裁剪区域</param>
    /// <param name="isSaveSource">是否保存覆盖原始图片</param>
    private Bitmap Rotate(string filePath, string cutFilePath, float angle, float sx, float sy, Rectangle cutRectangle, bool isSaveSource)
    {
        Rectangle imgRectangle = new Rectangle(Convert.ToInt32(hidImgX.Value), Convert.ToInt32(hidImgY.Value), Convert.ToInt32(hidImgWidth.Value), Convert.ToInt32(hidImgHeight.Value));

        int EditMainWidth = Convert.ToInt32(hidEditMainWidth.Value);
        int EditMainHeight = Convert.ToInt32(hidEditMainHeight.Value);
        Bitmap b = new Bitmap(filePath);
        angle = -1 * angle % 360;            //弧度转换
        double radian = angle * Math.PI / 180.0;
        double cos = Math.Cos(radian);
        double sin = Math.Sin(radian);
        //原图的宽和高
        int w = b.Width;
        int h = b.Height;
        //int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
        //int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
        int W = EditMainWidth;
        int H = EditMainHeight;
        //目标位图
        Bitmap dsImage = new Bitmap(W, H);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //计算偏移量
        Point Offset = new Point((W - w) / 2, (H - h) / 2);
        //构造图像显示区域：让图像的中心与窗口的中心点一致
        Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
        //Rectangle rect = new Rectangle(0, 0, EditMainWidth, EditMainWidth);
        Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
        g.TranslateTransform(center.X, center.Y);
        g.RotateTransform(360 - angle);
        g.ScaleTransform(sx, sy);
        //恢复图像在水平和垂直方向的平移
        g.TranslateTransform(-center.X, -center.Y);
        g.Clear(Color.White);
        g.DrawImage(b, rect);
        //重至绘图的所有变换
        g.ResetTransform();
        g.Save();
        g.Dispose();
        b.Dispose();
        if (isSaveSource)
        {
	    //弹出进入消息
            //dsImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            imgRectangle.Width = (dsImage.Width > imgRectangle.X + imgRectangle.Width ? imgRectangle.Width : dsImage.Width - imgRectangle.X);
            imgRectangle.Height = (dsImage.Height > imgRectangle.Y + imgRectangle.Height ? imgRectangle.Height : dsImage.Height - imgRectangle.Y);
            Bitmap cloneSource = dsImage.Clone(imgRectangle, dsImage.PixelFormat);
            cloneSource.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            //cloneSource.Dispose();
            return cloneSource;
        }
        
        if (cutRectangle != Rectangle.Empty)
        {

	    cutRectangle.Width = (dsImage.Width > cutRectangle.X + cutRectangle.Width ? cutRectangle.Width : dsImage.Width - cutRectangle.X);
            cutRectangle.Height = (dsImage.Height > cutRectangle.Y + cutRectangle.Height ? cutRectangle.Height : dsImage.Height - cutRectangle.Y);
            Bitmap cloneBitmap = dsImage.Clone(cutRectangle, dsImage.PixelFormat);
            dsImage.Dispose();
            if (!string.IsNullOrEmpty(cutFilePath))
            {
             
                cloneBitmap.Save(cutFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                
            }
            return cloneBitmap;
        }
        else
        {
	    return null;
        }
    }

    /// <summary>
    /// 刷新重置
    /// </summary>
    private void RefreshAll()
    {
        hidSourceFilePath.Value = Session["SourceFilePath"].ToString();
        hidSourceFileName.Value = Session["SourceFileName"].ToString();
        hidSourceWidth.Value = Session["SourceWidth"].ToString();
        hidSourceHeight.Value = Session["SourceHeight"].ToString();
    }

    /// <summary>
    /// 清空重置
    /// </summary>
    private void ClearAll()
    {
        hidSourceFilePath.Value = string.Empty;
        Session["SourceFilePath"] = string.Empty;
        hidSourceFileName.Value = string.Empty;
        Session["SourceFileName"] = string.Empty;
        hidSourceWidth.Value = string.Empty;
        Session["SourceWidth"] = string.Empty;
        hidSourceHeight.Value = string.Empty;
        Session["SourceHeight"] = string.Empty;
        hidIsPopupOnload.Value = "0";
    }
    #endregion

    #region Some Events
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        
        string[] _arr = FileUpload1.FileName.Split('.');
        if (_arr.Length > 0)
        {
            string fileTypeArr = "|jpg|bmp|gif|png";
            string fileTypeName = _arr[_arr.Length - 1];
            if (fileTypeArr.IndexOf("|" + fileTypeName.ToLower() + "|") >= 0)
            {
                string msg = string.Empty;
                string newFileName = EditBase.GetTimeNumber() + EditBase.GetRND(100, 999).ToString();

                Session["newFileN"] = newFileName;

                if (3 * 1024 * 1024 > FileUpload1.PostedFile.ContentLength)
                {
                    System.Drawing.Image bigImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
                    bigImage.Save(Server.MapPath(uploadFilePath + newFileName + postfixEarliest + ".jpg"));

                  
                    System.Drawing.Image smallImage = EditBase.GetThumbnailImageHeight(bigImage, Server.MapPath(uploadFilePath + newFileName + postfixSource + ".jpg"), 420);

                    
                    System.Drawing.Image smallImageTemp = EditBase.GetThumbnailImageHeight(bigImage, Server.MapPath(uploadFilePath + "_" + newFileName + postfixSource + ".jpg"), 420);

                   
                    //string[] arr = smallSourceSize.Split('*');

                    int colbitWidth = bigImage.Width;
                    int colbitHeight = bigImage.Height;

                    int smallWidth = colbitWidth;
                    int smallHeight = colbitHeight;
                    int mulip = 1;
                    if (colbitHeight + colbitWidth > CountValue)
                    {
                        mulip = (colbitWidth + colbitHeight) / CountValue;
                        if (mulip > 0)
                        {
                            smallHeight = Convert.ToInt32(colbitHeight / mulip);
                            smallWidth = Convert.ToInt32(colbitWidth / mulip);
                        }
                    }
        
                    //System.Drawing.Image smallSourceImage = EditBase.GetThumbnailImage(bigImage, Server.MapPath(uploadFilesSmall + newFileName + postfixSmallSource + ".jpg"), smallWidth, smallHeight);
                    //Session["SourceFilePath"] = uploadFilePath.Replace("~/", string.Empty);

                    Session["SourceFilePath"] = Page.ResolveUrl("~") + uploadFilePath.Replace("~/", string.Empty);

                    Session["SourceFileName"] = newFileName + postfixSource;
                    Session["SourceWidth"] = smallImageTemp.Size.Width.ToString();
                    Session["SourceHeight"] = smallImageTemp.Size.Height.ToString();

                    bigImage.Dispose();
                    smallImage.Dispose();
                    smallImageTemp.Dispose();
                    //smallSourceImage.Dispose();
                    divSmallSource.Visible = false;
                    imgSmallSource.ImageUrl = uploadFilesSmall + newFileName + postfixSmallSource + ".jpg";
                    lnkShowEarliest.NavigateUrl = uploadFilePath + newFileName + postfixEarliest + ".jpg";
                    RefreshAll();
                    //RegisterJSMessage(EditBase.RegisterJSAlert(ConfigurationManager.AppSettings["UploadSuccess"+this.LanguageTag]));
                }
                else
                {
                    RegisterJSMessage(EditBase.RegisterJSAlert(ConfigurationManager.AppSettings["FileSizeError"+this.LanguageTag]));
                }
            }
            else
            {
                RegisterJSMessage(EditBase.RegisterJSAlert(ConfigurationManager.AppSettings["IncorrectFileType"+this.LanguageTag]));
            }
        }
        else
        {
            RegisterJSMessage(EditBase.RegisterJSAlert(ConfigurationManager.AppSettings["UploadUnsuccess"+this.LanguageTag]));
        }
    }

    protected void btnToEdit_Click(object sender, EventArgs e)
    {
        divSmallSource.Visible = false;
        RefreshAll();
    }

    protected void btnToSave_Click(object sender, EventArgs e)
    {

        Rectangle cutRectangle;

        if (IsCut==0)
        {
            this.CutImage();
        }

        if (hidIsCut.Value == "1")
        {
            cutRectangle = new Rectangle(int.Parse(hidCutX.Value), int.Parse(hidCutY.Value), int.Parse(hidCutWidth.Value), int.Parse(hidCutHeight.Value));
        }
        else
        {
            cutRectangle = Rectangle.Empty;
        }
        Bitmap colsoure = null;
        if (IsBtnCut == 1)
        {
            colsoure = Rotate(Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), Server.MapPath(uploadFilePath + hidSourceFileName.Value.Replace(postfixSource, postfixCut) + ".jpg"), float.Parse(hidAngle.Value), float.Parse(hidSX.Value), float.Parse(hidSY.Value), cutRectangle, true);
        }
        else
        {
            colsoure = Rotate(Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), "", float.Parse(hidAngle.Value), float.Parse(hidSX.Value), float.Parse(hidSY.Value), cutRectangle, false);
        }
       if (colsoure == null)
       {
           return;
       }


       int colbitWidth = colsoure.Width;
       int colbitHeight = colsoure.Height;

         int smallWidth = colbitWidth;
        int smallHeight = colbitHeight;
        int mulip = 1;
        if (colbitHeight + colbitWidth > CountValue)
        {
            mulip = (colbitWidth + colbitHeight) / CountValue;
            if (mulip > 0)
            {
                smallHeight = Convert.ToInt32(colbitHeight / mulip);
                smallWidth = Convert.ToInt32(colbitWidth / mulip);
            }
        }

        EditBase.SaveSmallPic(Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), Server.MapPath(uploadFilesSmall + hidSourceFileName.Value.Replace(postfixSource, postfixSmall) + ".jpg"), smallWidth, smallHeight, ImageFormat.Jpeg);
        
        string strBig = Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg");
        string strSmall = Server.MapPath(uploadFilesSmall + hidSourceFileName.Value.Replace(postfixSource, postfixSmall) + ".jpg");
        lblEl.Text = strBig;
        lblSmall.Text = strSmall;
        Session["ImgPath"] = hidSourceFileName.Value;
        string filePath = Server.MapPath(uploadFilePath + "_" + hidSourceFileName.Value + ".jpg");
        FileInfo fi = new FileInfo(filePath);
       
        fi.Delete();
        
        if (hidIsPopupOnload.Value == "1")
        {
            RegisterJSMessage("<script language=\"javascript\" type=\"text/javascript\">$(function(){alert(\"" + ConfigurationManager.AppSettings["SaveSuccess"+this.LanguageTag] + "\");window.opener.fillImage('" + hidSourceFileName.Value + "');window.close();/*openPopup();*/});</script>");
        }
        else
        {
            RegisterJSMessage(EditBase.RegisterJSAlert("" + ConfigurationManager.AppSettings["SaveSuccess"+this.LanguageTag]));
        }
        ClearAll();
        IsCut = 0;
        IsBtnCut = 0;
       
        //Response.Redirect(Request.Url.ToString());
    }

    protected void btnToCut_Click(object sender, EventArgs e)
    {
        IsBtnCut = 1;
        this.CutImage();       
    }

    private void CutImage()
    {
        Rectangle cutRectangle = new Rectangle(int.Parse(hidCutX.Value), int.Parse(hidCutY.Value), int.Parse(hidCutWidth.Value), int.Parse(hidCutHeight.Value));
        Bitmap cutBitmap = Rotate(Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), float.Parse(hidAngle.Value), float.Parse(hidSX.Value), float.Parse(hidSY.Value), cutRectangle, false);

        //Session["SourceFilePath"] = uploadFilePath.Replace("~/", string.Empty);

        Session["SourceFilePath"] = Page.ResolveUrl("~") + uploadFilePath.Replace("~/", string.Empty);

        Session["SourceFileName"] = hidSourceFileName.Value;
        Session["SourceWidth"] = cutBitmap.Size.Width.ToString();
        Session["SourceHeight"] = cutBitmap.Size.Height.ToString();
        cutBitmap.Dispose();
       
        IsCutYOrN = "1";
        IsCut = 1;
        RefreshAll();
       
    }

    protected void btnToReset_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath(uploadFilePath + "_" + hidSourceFileName.Value + ".jpg");
        FileInfo fi = new FileInfo(filePath);
        fi.CopyTo(Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg"), true);
    }

    protected void btnToDelete_Click(object sender, EventArgs e)
    {
        string elfilePath = Server.MapPath(uploadFilePath + Session["newFileN"].ToString() + postfixEarliest + ".jpg");
        FileInfo fi = new FileInfo(elfilePath);
        if (fi.Exists)
        {
            fi.Delete();
        }
        string filePath = Server.MapPath(uploadFilePath + hidSourceFileName.Value + ".jpg");
        fi = new FileInfo(filePath);
        if (fi.Exists)
        {
            fi.Delete();
            string filePathNew = Server.MapPath(uploadFilePath + "_" + hidSourceFileName.Value + ".jpg");
            fi = new FileInfo(filePathNew);
            if (fi.Exists)
            {
                fi.Delete();
            }
        }
        if (hidIsPopupOnload.Value == "1")
        {
            RegisterJSMessage("<script language=\"javascript\" type=\"text/javascript\">$(function(){openPopup();});</script>");
        }
        ClearAll();
    }
    #endregion
}
